﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Asset
{
    public class AsyncAsset<T> : Asset<T> where T : UnityEngine.Object
    {
        public event Action<T> onComplete;
        private AssetBundleRequest request;

        public AsyncAsset(string name, IAsyncBundle bundle) : base(name, bundle)
        {

        }

        protected override void initialize()
        {

        }

        public override IEnumerator doLoad()
        {
            if (this.Status == AsyncStatus.Waiting && this.Bundle.bundle != null)
            {
                this.asyncStatus = AsyncStatus.Running;
                request = this.Bundle.bundle.LoadAssetAsync<T>(this.resName);
                yield return request;
            }
            else if (this.Status == AsyncStatus.Running)
            {
                if (this.request.isDone)
                {
                    this.asyncStatus = AsyncStatus.Finish;
                    this.result = request.asset as T;
                    invokeEvent();
                }
            }
        }

        protected void invokeEvent()
        {
            if (this.onComplete != null)
                this.onComplete(this.Result);
        }


    }

}
